from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import models
from app.db.session import get_db
from app.schemas import AlertHistoryResponse
from typing import List
from datetime import datetime, timedelta

router = APIRouter()


@router.get("/history", response_model=List[AlertHistoryResponse])
def read_alert_history(
        rule_id: int = None,
        start_time: datetime = None,
        end_time: datetime = None,
        skip: int = 0,
        limit: int = 100,
        db: Session = Depends(get_db)
):
    query = db.query(models.AlertHistory)

    if rule_id:
        query = query.filter(models.AlertHistory.rule_id == rule_id)

    if start_time:
        query = query.filter(models.AlertHistory.trigger_time >= start_time)

    if end_time:
        query = query.filter(models.AlertHistory.trigger_time <= end_time)

    if not start_time and not end_time:
        # 默认显示最近7天的记录
        default_start = datetime.now() - timedelta(days=7)
        query = query.filter(models.AlertHistory.trigger_time >= default_start)

    history = query.order_by(models.AlertHistory.trigger_time.desc()) \
        .offset(skip).limit(limit).all()
    return history